﻿using Business;
using Service;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Utility;

namespace WXDataService
{
    public partial class ServiceForm : System.Windows.Forms.Form
    {
      
        private HttpListener m_Listener;// 监听线程

       
        //private Thread m_ReceiveThread = null;
        private Thread m_ReceiveThread = null; // 接收线程
        private Thread m_threadForSendData= null; // 线程发送数据推送
        private Thread m_threadForClearDataChangeLog = null; // 线程清理日志改变数据
        private Thread DealInnerComm = null; // 线程清理日志改变数据
        private Thread m_threadTimerData = null; // 定时器
        //private Thread m_threadForSendEcgData= null; // 线程发送心电数据推送
            

        //private string m_ListerURL = ""; //Http监听地址
        //Thread m_threadForData = null;
        public ServiceForm()
        {
            InitializeComponent();
            EventUtility.ShowMsg += new EventUtility.OnShowMsgDelegate(EventUtility_ShowMsg);

            ShowMsg("程序开始运行", false);
            if (m_Listener == null)
            {
                m_Listener = new HttpListener();
                m_Listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问
                m_Listener.Prefixes.Add(AppConfig.HttpIP);
            }

            if (m_ReceiveThread == null)
            {
                m_ReceiveThread = new Thread(new ThreadStart(ThreadStartProc)); //开启监听线程
                m_ReceiveThread.IsBackground = true;
                m_ReceiveThread.Start();
            }


            DealInnerCommData();//启动内部通讯

            if (m_threadForSendData == null)
            {
                m_threadForSendData = new Thread(this.PushData); //开启数据推送
                m_threadForSendData.IsBackground = true;
                m_threadForSendData.Start();
            }

            
            //if (m_threadTimerData == null)
            //{
            //    m_threadTimerData = new Thread(this.GetDeviceBindInfo); //开启数据推送
            //    m_threadTimerData.IsBackground = true;
            //    m_threadTimerData.Start();
            //}

            if (m_threadForClearDataChangeLog==null) {
                //清除日志变化数据 
                m_threadForClearDataChangeLog = new Thread(this.ClearDataChangeLog);
                m_threadForClearDataChangeLog.IsBackground = true;
                m_threadForClearDataChangeLog.Start();
            }
           

            //if (m_threadForSendEcgData == null)
            //{
            //    m_threadForSendEcgData = new Thread(this.PushEcgData); //开启心电数据推送
            //    m_threadForSendEcgData.IsBackground = true;
            //    m_threadForSendEcgData.Start();
            //}

        }




        /// <summary>
        /// 监听线程
        /// </summary>
        private void ThreadStartProc()
        {
            try
            {
                m_Listener.Start();
                ShowMsg("http监听成功,监听地址" + AppConfig.HttpIP, false);
                LogUtility.Debug("m_ReceiveThread", "监听成功 ");
            }
            catch (Exception ex)
            {
                ShowMsg("监听失败,原因:" + ex.Message, true);
                LogUtility.Debug("m_ReceiveThread", "监听失败,原因:" + ex.Message);
                return;
            }

            while (true)
            {
                HttpListenerContext context;
                try
                {
                    context = m_Listener.GetContext();
                }
                catch (Exception ex)
                {
                    if (!ex.Message.Contains("正在中止线程"))
                    {
                        ShowMsg("出现异常,原因:" + ex.Message, true);
                        LogUtility.Debug("m_ReceiveThread", "监听失败,原因:" + ex.Message);
                    }
                    continue;
                }

                if (context.Request.HasEntityBody)
                    DealClientData(context.Request, context.Response);
            }
        }

        /// <summary>
        /// 启动线程处理客户端的HTTP请求数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        private void DealClientData(HttpListenerRequest request, HttpListenerResponse response)
        {
            DealHttpDataBusiness dataBusiness = new DealHttpDataBusiness(request, response);
            //dataBusiness.ShowMsgEvent += ShowMsg;
            Thread ClientThread = new Thread(new ThreadStart(dataBusiness.DealRequestData));
            ClientThread.IsBackground = true;
            ClientThread.Start();
        }

        private void PushData()
        {
            PushDataSerivce.service.PushWDData();
            //FirstAidCenterBLL.Instance.GetFirstAidCenterInfo(null);
        }


        /// <summary>
        /// 定时获取设备绑定车辆信息
        /// </summary>
        //private void GetDeviceBindInfo()
        //{
        //    PushDataSerivce.service.DeviceBindService();
        //}


        private void DealInnerCommData()
        {
            DealInnerCommService.Instance.start();
        }


        private void ClearDataChangeLog()
        {
            PushDataSerivce.service.ClearDataChangeLog();
            //FirstAidCenterBLL.Instance.GetFirstAidCenterInfo(null);
        }

        //private void PushEcgData()
        //{
        //    PushDataSerivce.service.PushEcgData();
        //    //FirstAidCenterBLL.Instance.GetFirstAidCenterInfo(null);
        //}


        /// <summary>
        /// 调试信息提示信息
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="isError"></param>
        private void ShowMsg(string msg, bool isError)
        {
            ShowListViewMessage(listView1, isError, msg);
        }



        /// <summary>
        /// 显示业务类消息
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="isError"></param>
        void EventUtility_ShowMsg(string msg, bool isError)
        {
            ShowMsg(msg, isError);
            if (isError)
                LogUtility.Error("ServiceForm/EventUtility_ShowMsg", msg);
        }


        /// <summary>
        /// 显示信息到ListView
        /// </summary>
        /// <param name="lv"></param>
        /// <param name="messageLevel"></param>
        /// <param name="msg"></param>
        private void ShowListViewMessage(ListView lv, bool messageLevel, string msg)
        {

            if (lv.Items.Count > 1000)
                lv.Items.Clear();

            ListViewItem lvItem = new ListViewItem();
            //lvItem.UseItemStyleForSubItems = false;
            if (messageLevel)
            {
                lvItem.ImageIndex = 3;
                lvItem.ForeColor = Color.Red;
            }
            else
            {
                lvItem.ImageIndex = 0;
                lvItem.ForeColor = Color.Green;
            }

            lvItem.Text = "";
       

            ListViewItem.ListViewSubItem lvsItem = new ListViewItem.ListViewSubItem();
            lvsItem.Text = DateTime.Now.ToString();
            lvItem.SubItems.Add(lvsItem);

            lvsItem = new ListViewItem.ListViewSubItem();
            lvsItem.Text = msg;
            lvItem.SubItems.Add(lvsItem);

            lv.Items.Insert(0, lvItem);//在第一行插
        }

        private void ServiceForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            PushDataSerivce.service.StopWork();
        }


    }
}
